<template>
  <div class="mod-config" style="margin-left:30px;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)">
    <basic-container>
      <div>
        <el-row>
          <el-col :span="12">
            <el-row>
              <span style="font-size:12px;margin-right:20px">{{title}}</span>
              <template v-if="this.materialGroupId != '-1'">
                <el-button type="text" icon="el-icon-edit" @click="handleGroupRename">重命名</el-button>
                <el-button type="text" icon="el-icon-delete" @click="handleGroupDelete">删除</el-button>  
              </template>
              
            </el-row>
          </el-col>
          <el-col :span="12" class="right">
            <el-upload
              class="upload-demo"
              :headers="headers"
              :action="uploadImgUrl"
              :on-success="handleUploadSuccess"
              :before-upload="handleBeforeUpload"
              :on-error="handleUploadError"
              name="file"
              :show-file-list="false">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <!-- <el-button type="primary">点击上传</el-button> -->
          </el-col>
        </el-row>
      </div>
      <div style="margin-top:20px">
        <template v-if="dataList.length > 0">
          <el-row v-for="(items,index) in dataList" :key="index">
            <el-col :span="4" v-for="(item, index1) in items" :key="index1">
              <div style="margin-right:10px;padding:10px;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)">
                <div>
                  <el-image style="width: 100%; height: 170px" :src="item.materialUrl" fit="contain" :preview-src-list=[item.materialUrl]></el-image>
                </div>
                <div class="title">
                  <el-checkbox v-model="item.checked" v-if="hasDialog"></el-checkbox>
                  <span>{{item.materialName}}</span>
                </div>
                <el-row>
                  <el-col :span="6">
                    <div class="centered">
                      <el-button type="text" @click="handleUpdateName(item)">改名</el-button>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div class="centered">
                      <el-upload
                        class="upload-demo"
                        :headers="headers"
                        :action="uploadImgUrl"
                        :on-success="handleEditUploadSuccess"
                        :before-upload="handleBeforeUpload"
                        :on-error="handleUploadError"
                        name="file"
                        :show-file-list="false">
                        <el-button type="text" @click="handleEditImage(item)">替换</el-button>
                      </el-upload>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div class="centered">
                      <el-dropdown trigger="click" @visible-change="handleOpenGroup(item, $event)" @command="handleCommand(item, $event)">
                        <el-button type="text">分组<i class="el-icon-arrow-down el-icon--right"></i></el-button>
                        <el-dropdown-menu slot="dropdown" >
                          <el-dropdown-item :command="group.id" v-for="(group, index1) in item.availableGroups" :key="index1">{{group.materialGroupName}}</el-dropdown-item>
                          
                        </el-dropdown-menu>
                      </el-dropdown>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div class="centered">
                      <el-button type="text" @click="handleMaterialDel(item)">
                        <span style="color:#FF0000">删除</span>
                      </el-button>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-col>
          </el-row>
        </template>
        <template v-else>
          <el-empty description="暂无数据"></el-empty>
        </template>
        
      </div>

      <div class="avue-crud__pagination">
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="queryParams.pageIndex"
          :page-sizes="[12]"
          :page-size="queryParams.pageSize"
          :total="totalPage"
          background
          layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>
      </div>
      
    </basic-container>
  </div>
</template>

<script>
import store from "@/store";
import {addObj, fetchList, putObj, delObj, moveMaterialGroup} from '@/api/material/material';
import {getAvailableMaterialGroups} from '@/api/material/group';
import { computedStyle } from "vue-json-editor/assets/jsoneditor";

export default {
  data(){
    return{
      totalPage: 0,
      dataListLoading: false,
      
      queryParams:{
        materialGroupId:'',
        pageIndex: 1,
        pageSize: 12,
      },

      dataList:[],
      soruceDataList:[],

      //uploadImgUrl: "https://admin.mnyourui.com/admin/sys-file/upload", // 上传的图片服务器地址
      uploadImgUrl: "/admin/sys-file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + store.getters.access_token,
        //Authorization: "Bearer pig::admin::5a96e042-aa51-4061-ba70-1b17dac2a07e"
      },
      isImgCheck:false,
      title:this.materialGroupName,
      currentUpdateMaterialItem:null
    }
  },
  props:{
    materialGroupId:{
      type:String,
      default:''
    },
    materialGroupName:{
      type:String,
      default:''
    },

    // 是否是弹窗显示
    hasDialog:{
      type:Boolean,
      default:false
    },

    // 是否是单选
    hasSingle:{
      type:Boolean,
      default:false
    }
  },
  created(){
    //this.getDataList()
  },
  methods:{
    
    /**
     * 初始化
     */
    init(){
      this.getDataList()
    },

    /**
     * 获取列表数据
     */
    getDataList(){
      this.dataList = []
      this.soruceDataList = []
      this.queryParams.materialGroupId = this.materialGroupId
      fetchList({
        materialGroupId: this.queryParams.materialGroupId,
        current: this.queryParams.pageIndex,
        size: this.queryParams.pageSize
      }).then(res=>{
        this.soruceDataList = res.data.data.records;
        let data = res.data.data.records
        data.forEach(item=>{
          this.$set(item, 'checked', false)
          this.$set(item, 'availableGroups', [{id:'-99', materialGroupName:'暂无'}])
          //item.materialUrl = this.imageBaseUrl + item.materialUrl
          item.materialUrl = item.materialUrl
        })
        let rows = null
        for(let i = 0; i < data.length; i++){
          let mod = i % 6
          if(mod == 0){
            rows = []
            rows.push(data[i])
            this.dataList.push(rows)
          } else {
            rows.push(data[i])
          }
        }					
        console.log(this.dataList)
        this.totalPage = res.data.data.total;
      })
    },

    /**
     * 素材上传成功
     */
    handleUploadSuccess(res) {
      if(res.code == 0){
        this.addMaterial(res)
        this.loading.close();
      } else {
        this.$message({
          type: "error",
          message: res.msg,
        });
        this.loading.close();
      }  
    },

    /**
     * 修改素材
     */
    handleEditUploadSuccess(res){
      if(res.code == 0){
        this.updateMaterial(res)
        this.loading.close();
      } else {
        this.$message({
          type: "error",
          message: res.msg,
        });
        this.loading.close();
      }  
    },

    /**
     * 添加素材
     */
    addMaterial(res){
      let params = {
        materialName:res.data.fileName,
        materialUrl: this.imageBaseUrl + res.data.url,
        materialGroupId: this.materialGroupId
      }
      addObj(params).then(res=>{
         this.$message.success("上传成功");
         this.getDataList();
      })
    },

    /**
     * 修改素材
     */
     updateMaterial(res){
      let params = {
        id: this.currentUpdateMaterialItem.id,
        materialUrl: this.imageBaseUrl + res.data.url,
      }
      putObj(params).then(res=>{
         this.$message.success("修改成功");
         this.getDataList();
      })
    },

    async handleBeforeUpload(file) {
      if (this.isImgCheck) {
        const result = await this.checkImg(file);    //若没有上传图片不通过， 就直接跳出
        if (!result) return;
      } else {
        this.loading = this.$loading({
          lock: true,
          text: "上传中",
          background: "rgba(0, 0, 0, 0.7)",
        });
        this.$emit("beforeUpload", file);
      }
    },

    handleUploadError() {
      this.$message({
        type: "error",
        message: "上传失败",
      });
      this.loading.close();
    },

    checkImg(file) {
      const isSize = new Promise((resolve, reject) => {
        const _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = () => {
          const valid = img.width === this.imgW && img.height === this.imgH;
          valid ? resolve() : reject();
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          this.loading = this.$loading({
            lock: true,
            text: "上传中",
            background: "rgba(0, 0, 0, 0.7)",
          });
          this.$emit("beforeUpload", file);
          return file;
        },
        () => {
          this.$message({
            type: "error", 
            message: `图片尺寸大小必须为${this.imgW}*${this.imgH}`
          }); //  我这里是将upload组件进一步封装了， imgW, imgH是图片限制的条件参数
          return Promise.reject(false);
        }
      );
      return isSize;
    },



    /**
     * 每页数
     */
    sizeChangeHandle(val) {
      this.queryParams.pageSize = val;
      this.queryParams.pageIndex = 1;
      this.getDataList();
    },

    /**
     * 当前页
     */
    currentChangeHandle(val) {
      this.queryParams.pageIndex = val;
      this.getDataList();
    },

    /**
     * 改名
     */
    handleUpdateName(item){
      this.$prompt('请输入素材名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: item.materialName
      }).then(({ value }) => {
        item.materialName = value
        putObj(item).then(res=>{
          this.getDataList()
          this.$message.success("修改成功");
        })
      }).catch(() => {  
      });
    },

    /**
     * 链接
     */
    handleMaterialLink(item){
      this.$prompt('素材链接', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: item.materialUrl
      }).then(({ value }) => {
        this.$message({
          type: 'success',
          message: '你的素材名是: ' + value
        });
      }).catch(() => {
      });
    },

    /**
     * 修改图片
     */
    handleEditImage(item){
      console.log(item)
      this.currentUpdateMaterialItem = item
    },

    /**
     * 删除
     */
    handleMaterialDel(item){
      this.$confirm("是否确认删除该素材？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
      .then(function () {
        return delObj(item.id);
      })
      .then((data) => {
        this.$message.success("删除成功");
        if(this.soruceDataList.length <= 1 && this.queryParams.pageIndex > 1){
          this.queryParams.pageIndex--;
        }
        this.getDataList();
      })
      .catch(() => {});
    },

    /**
     * 重命名组名
     */
    handleGroupRename(){
      this.$emit("updateMaterialGroup", (value)=>{
        // 成功修改组名, 更新子组件
        this.title = value
      })
    },

    /**
     * 删除分组
     */
    handleGroupDelete(){
      this.$emit("deleteMaterialGroup", (value)=>{
        // 成功删除组名, 更新子组件
      })
    },

    /**
     * 打开菜单
     */
    handleOpenGroup(item, isOpen){
      if(isOpen){
        getAvailableMaterialGroups({
          id: item.materialGroupId
        }).then(res=>{
          let data = res.data.data
          item.availableGroups = data
          if(this.materialGroupId != '-1'){
            item.availableGroups.unshift({id:'-1', materialGroupName:'默认分组'})
          }
        })
      }
    },

    /**
     * 移动分组
     */
    handleCommand(item, command){
      if(command == '-99'){
        return
      }
      
      moveMaterialGroup({
        id: item.id,
        targetMaterialGroupId: command,
      }).then(res=>{
        this.$message.success("移动成功");
        if(this.soruceDataList.length <= 1 && this.queryParams.pageIndex > 1){
          this.queryParams.pageIndex--;
        }
        this.getDataList();
      })

    },

    /**
     * 获取选择的素材
     */
    getSelectedMaterial(callback){
      let items = []      
      this.dataList.forEach(data=>{
        data.forEach(item=>{
          if(item.checked){
            items.push(item)
          }
        })
      })
      //this.$bus.$emit("getSelectMaterial", items)
      callback(items)
    }
  }
}
</script>

<style scoped>

.title{
  font-size: 12px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.centered{
  display: flex;
  align-items: center;
  justify-content: center;
}

.right{
  display: flex;
  align-items: right;
  justify-content: right;
  
}
</style>